<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ollama 聊天助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.8rem;
            margin-bottom: 15px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.2rem;
            opacity: 0.9;
            font-weight: 300;
        }

        .content {
            padding: 50px;
        }

        .config-section {
            margin-bottom: 40px;
            background: linear-gradient(135deg, #fff9e6 0%, #fff3cd 100%);
            border: 1px solid #ffeaa7;
            border-radius: 12px;
            padding: 20px;
            color: #856404;
        }

        .config-section h4 {
            margin-bottom: 10px;
            color: #856404;
            font-size: 14px;
            font-weight: 600;
        }

        .config-section p {
            font-size: 13px;
            line-height: 1.5;
            margin: 0;
        }

        .query-section {
            margin-bottom: 40px;
        }

        .query-section h2 {
            color: #333;
            margin-bottom: 25px;
            font-size: 1.6rem;
            font-weight: 600;
        }

        .input-group {
            margin-bottom: 25px;
        }

        .input-group label {
            font-weight: 600;
            margin-bottom: 8px;
            display: block;
        }

        .input-group textarea {
            width: 100%;
            padding: 24px;
            border: 2px solid #e1e8ed;
            border-radius: 18px;
            font-size: 18px;
            resize: vertical;
            min-height: 200px;
            transition: all 0.3s ease;
            font-family: inherit;
            line-height: 1.7;
        }

        .input-group textarea:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        .input-group textarea::placeholder {
            color: #999;
            font-style: italic;
        }

        .mode-selector {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
        }

        .mode-option {
            flex: 1;
            padding: 15px;
            border: 2px solid #e1e8ed;
            border-radius: 12px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .mode-option:hover {
            border-color: #4facfe;
        }

        .mode-option.selected {
            border-color: #4facfe;
            background: linear-gradient(135deg, #f8fcff 0%, #f0f9ff 100%);
        }

        .mode-option h3 {
            font-size: 1.1rem;
            margin-bottom: 8px;
            color: #333;
        }

        .mode-option p {
            font-size: 0.9rem;
            color: #666;
        }

        .btn-group {
            display: flex;
            gap: 15px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 18px 35px;
            border-radius: 15px;
            font-size: 17px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            flex: 1;
            box-shadow: 0 4px 15px rgba(79, 172, 254, 0.3);
        }

        .btn-primary:hover:not(:disabled) {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4);
        }

        .btn-primary:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            transform: none;
        }

        .result-section {
            border-top: 2px solid #f0f0f0;
            padding-top: 40px;
        }

        .result-section h3 {
            color: #333;
            margin-bottom: 25px;
            font-size: 1.4rem;
            font-weight: 600;
        }

        .result-display {
            min-height: 180px;
            border: 2px dashed #e1e8ed;
            border-radius: 15px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .result-display.loading {
            border-color: #4facfe;
            background: linear-gradient(135deg, #f8fcff 0%, #f0f9ff 100%);
        }

        .result-display.success {
            border-color: #28a745;
            background: linear-gradient(135deg, #f8fff9 0%, #f0fff4 100%);
            border-style: solid;
        }

        .result-display.error {
            border-color: #dc3545;
            background: linear-gradient(135deg, #fff8f8 0%, #fff0f0 100%);
            border-style: solid;
        }

        .loading-spinner {
            font-size: 2.5rem;
            color: #4facfe;
            margin-bottom: 20px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .result-text {
            background: white;
            padding: 25px;
            border-radius: 12px;
            border-left: 5px solid #28a745;
            text-align: left;
            font-size: 16px;
            line-height: 1.7;
            color: #333;
            white-space: pre-wrap;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .stream-text {
            background: white;
            padding: 25px;
            border-radius: 12px;
            border-left: 5px solid #007bff;
            text-align: left;
            font-size: 16px;
            line-height: 1.7;
            color: #333;
            white-space: pre-wrap;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            min-height: 100px;
        }

        .error-text {
            color: #dc3545;
            font-size: 16px;
            font-weight: 500;
        }

        .empty-text {
            color: #6c757d;
            font-size: 16px;
            line-height: 1.6;
        }

        .timestamp {
            margin-top: 20px;
            font-size: 13px;
            color: #6c757d;
            text-align: right;
            font-style: italic;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 15px;
            }

            .header {
                padding: 30px 20px;
            }

            .header h1 {
                font-size: 2.2rem;
            }

            .content {
                padding: 30px 20px;
            }

            .input-group textarea {
                min-height: 120px;
                padding: 15px;
            }

            .btn-group {
                flex-direction: column;
            }

            .btn-primary {
                padding: 15px 25px;
                font-size: 16px;
            }

            .mode-selector {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>🤖 Ollama 聊天助手</h1>
        <p>基于AI的智能对话系统</p>
    </div>

    <div class="content">
        <div class="config-section">
            <h4>💡 配置信息</h4>
            <p>当前使用的是 <span id="currentProfile">加载中...</span> 配置，Ollama服务地址: <span id="currentUrl">加载中...</span>，模型: <span id="currentModel">加载中...</span></p>
            <p style="margin-top: 10px;">🔧 已注册工具：数学计算工具、天气查询工具</p>
        </div>

        <div class="query-section">
            <h2>📝 输入您的问题</h2>
            
            <div class="mode-selector">
                <div class="mode-option selected" data-mode="simple">
                    <h3>简单模式</h3>
                    <p>一次性返回完整回答</p>
                </div>
                <div class="mode-option" data-mode="stream">
                    <h3>流式模式</h3>
                    <p>实时流式返回回答</p>
                </div>
            </div>
            
            <div class="input-group">
                <textarea
                        id="promptInput"
                        placeholder="请输入您想问的问题，例如：
                        • 你好，介绍下你自己！
                        • 什么是人工智能？
                        • 请解释一下机器学习的基本概念
                        • 如何学习编程？
                        • 请计算 15 加上 27 等于多少？
                        • 北京今天的天气怎么样？
                        • 100 除以 4 等于多少？
                        • 上海的天气如何？"
                ></textarea>
            </div>
            
            <div class="btn-group">
                <button id="chatBtn" class="btn-primary">
                    🚀 开始对话
                </button>
                <button id="clearBtn" class="btn-primary">
                    🗑️ 清空对话
                </button>
            </div>
        </div>

        <div class="result-section">
            <h3>💬 对话结果</h3>
            <div id="resultDisplay" class="result-display">
                <div class="empty-text">
                    🔍 等待对话中...
                    <br><br>请在上方输入您的问题并点击对话按钮
                    <br>系统将为您智能分析并返回结果
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const promptInput = document.getElementById('promptInput');
    const chatBtn = document.getElementById('chatBtn');
    const clearBtn = document.getElementById('clearBtn');
    const resultDisplay = document.getElementById('resultDisplay');
    const modeOptions = document.querySelectorAll('.mode-option');
    const currentProfile = document.getElementById('currentProfile');
    const currentUrl = document.getElementById('currentUrl');
    const currentModel = document.getElementById('currentModel');
    
    let selectedMode = 'simple';
    let streamController = null;

    // 初始化页面
    async function initPage() {
        try {
            const response = await fetch('/client/config');
            if (response.ok) {
                const configText = await response.text();
                // 解析配置信息
                const profileMatch = configText.match(/当前使用的配置: ([^,]+)/);
                const urlMatch = configText.match(/Ollama服务地址: ([^,]+)/);
                const modelMatch = configText.match(/模型: (.+)/);
                
                if (profileMatch) currentProfile.textContent = profileMatch[1].trim();
                if (urlMatch) currentUrl.textContent = urlMatch[1].trim();
                if (modelMatch) currentModel.textContent = modelMatch[1].trim();
            }
        } catch (error) {
            console.error('获取配置信息失败:', error);
            currentProfile.textContent = '未知';
            currentUrl.textContent = '未知';
            currentModel.textContent = '未知';
        }
    }

    // 模式选择
    modeOptions.forEach(option => {
        option.addEventListener('click', () => {
            modeOptions.forEach(opt => opt.classList.remove('selected'));
            option.classList.add('selected');
            selectedMode = option.dataset.mode;
        });
    });

    // 对话函数
    async function performChat(prompt) {
        if (!prompt.trim()) {
            alert('请输入对话内容');
            return;
        }

        // 设置加载状态
        setLoading(true);

        try {
            const apiUrl = selectedMode === 'stream' 
                ? `/client/stream/chat?prompt=${encodeURIComponent(prompt.trim())}`
                : `/client/simple/chat?prompt=${encodeURIComponent(prompt.trim())}`;

            if (selectedMode === 'stream') {
                // 流式处理
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let resultText = '';
                
                resultDisplay.className = 'result-display success';
                resultDisplay.innerHTML = `<div class="stream-text" id="streamResult"></div>`;
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    
                    const chunk = decoder.decode(value);
                    resultText += chunk;
                    document.getElementById('streamResult').textContent = resultText;
                }
                
                // 添加时间戳
                resultDisplay.innerHTML += `<div class="timestamp">📅 对话完成时间：${new Date().toLocaleString('zh-CN')}</div>`;
            } else {
                // 简单模式处理
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.text();
                showResult(result);
            }
        } catch (error) {
            showError(error.message || '对话失败，请检查网络连接或接口状态');
        } finally {
            setLoading(false);
        }
    }

    // 设置加载状态
    function setLoading(loading) {
        chatBtn.disabled = loading;

        if (loading) {
            chatBtn.innerHTML = '🔄 对话中...';
            resultDisplay.className = 'result-display loading';
            resultDisplay.innerHTML = `
                    <div class="loading-spinner">🔄</div>
                    <div style="font-size: 18px; font-weight: 500; margin-bottom: 10px;">AI正在思考您的问题...</div>
                    <div style="font-size: 14px; color: #6c757d;">
                        请稍候，系统正在智能解析并生成回答
                    </div>
                `;
        } else {
            chatBtn.innerHTML = '🚀 开始对话';
        }
    }

    // 显示成功结果
    function showResult(result) {
        resultDisplay.className = 'result-display success';
        resultDisplay.innerHTML = `
                <div class="result-text">${result}</div>
                <div class="timestamp">
                    📅 对话完成时间：${new Date().toLocaleString('zh-CN')}
                </div>
            `;
    }

    // 显示错误
    function showError(error) {
        resultDisplay.className = 'result-display error';
        resultDisplay.innerHTML = `
                <div class="error-text">
                    ❌ 对话失败<br><br>
                    ${error}
                </div>
                <div style="margin-top: 20px; font-size: 14px; color: #6c757d;">
                    <strong>💡 可能的解决方案：</strong><br>
                    • 检查网络连接是否正常<br>
                    • 确认Ollama服务是否正在运行<br>
                    • 验证接口地址是否正确<br>
                    • 尝试重新提交对话
                </div>
            `;
    }

    // 清空对话
    function clearChat() {
        resultDisplay.className = 'result-display';
        resultDisplay.innerHTML = `
                <div class="empty-text">
                    🔍 等待对话中...
                    <br><br>请在上方输入您的问题并点击对话按钮
                    <br>系统将为您智能分析并返回结果
                </div>
            `;
        promptInput.value = '';
        promptInput.focus();
    }

    // 绑定对话按钮事件
    chatBtn.addEventListener('click', () => {
        performChat(promptInput.value);
    });

    // 绑定清空按钮事件
    clearBtn.addEventListener('click', clearChat);

    // 绑定回车键事件
    promptInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && e.ctrlKey) {
            performChat(promptInput.value);
        }
    });

    // 页面加载完成后初始化
    window.addEventListener('load', initPage);
    
    // 自动聚焦到输入框
    promptInput.focus();
</script>
</body>
</html>